package com.krtech.wecard.module.sys.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.krtech.wecard.config.LakerConfig;
import com.krtech.wecard.framework.EasyAdminConstants;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.ext.mybatis.UserDataPower;
import com.krtech.wecard.framework.ext.mybatis.UserInfoAndPowers;
import com.krtech.wecard.framework.model.PageResponse;
import com.krtech.wecard.framework.model.PageVO;
import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.security.Inner;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.pub.dto.CardInfoVo;
import com.krtech.wecard.module.pub.entity.CardIdentityRelationInfo;
import com.krtech.wecard.module.pub.entity.CardInfoUser;
import com.krtech.wecard.module.pub.service.CardIdentityRelationInfoService;
import com.krtech.wecard.module.pub.service.CardInfoUserService;
import com.krtech.wecard.module.sys.entity.*;
import com.krtech.wecard.module.sys.enums.SysEnums;
import com.krtech.wecard.module.sys.mapper.SysUserMapper;
import com.krtech.wecard.module.sys.pojo.*;
import com.krtech.wecard.module.sys.service.*;
import com.krtech.wecard.module.sys.service.impl.SysDeptServiceImpl;
import com.krtech.wecard.module.sys.service.impl.SysUserServiceImpl;
import com.krtech.wecard.utils.DfsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.util.XmlUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author laker
 * @since 2021-08-05
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户管理")
@Slf4j
public class SysUserController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysUserRoleService sysUserRoleService;
    @Autowired
    LakerConfig lakerConfig;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysSchoolInfoService schoolInfoService;

    @Autowired
    private SysUserOperateLogService userOperateLogService;

    @Autowired
    private SysKeyValueService keyValueService;

    @Autowired
    private CardInfoUserService cardInfoUserService;

    @Autowired
    private CardIdentityRelationInfoService cardIdentityRelationInfoService;


//    @GetMapping
//    @ApiOperation(value = "分页查询")
//    public PageResponse pageAll(@RequestParam(required = false, defaultValue = "1") long page,
//                                @RequestParam(required = false, defaultValue = "10") long limit,
//                                Long deptId,
//                                String keyWord) {
//        Page roadPage = new Page<>(page, limit);
//        LambdaQueryWrapper<SysUser> queryWrapper = new QueryWrapper().lambda();
//        queryWrapper.eq(deptId != null, SysUser::getDeptId, deptId)
//                .and(StrUtil.isNotBlank(keyWord), i -> i.
//                        like(StrUtil.isNotBlank(keyWord), SysUser::getUserName, keyWord)
//                        .or().like(StrUtil.isNotBlank(keyWord), SysUser::getUserName, keyWord));
//        Page pageList = sysUserService.page(roadPage, queryWrapper);
//
//        return PageResponse.ok(pageList.getRecords(), pageList.getTotal());
//    }

//    @GetMapping("/page")
//    @ApiOperation(value = "分页查询")
//    public CommRes page(Page<SysUser> page, Long deptId, String keyword) {
//        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
//        if (deptId != null){
//            wrapper.eq(SysUser.COL_DEPT_ID,deptId);
//        }
//
//        if (StrUtil.isNotEmpty(keyword)){
//            wrapper.like(SysUser.COL_NICK_NAME,keyword)
//                    .or()
//                    .like(SysUser.COL_USER_CODE,keyword)
//                    .or()
//                    .like(SysUser.COL_PHONE,keyword)
//                    .or()
//                    .like(SysUser.COL_TAG,keyword);
//        }
//
//
//        Page<SysUser> userPage = sysUserService.page(page, wrapper);
//
//        return CommRes.ok(userPage);
//    }

    @GetMapping("/getUserInfo")
    @ApiOperation(value = "获得用户信息")
    public LoginVo getUserInfo(){
        LoginVo loginVo = new LoginVo();
        SysUser userInfo = LoginUtil.getUserInfo();

        loginVo.setSaTokenInfo(StpUtil.getTokenInfo());
        SysUser sysUser = sysUserService.getById(userInfo.getUserId());

        loginVo.setUserInfo(sysUser);
        loginVo.setRoleList(StpUtil.getRoleList());
        loginVo.setPermissionList(StpUtil.getPermissionList());
        return loginVo;
    }

    @PostMapping("/updateAvatarAndNickName")
    @ApiOperation(value = "更新用户昵称和头像")
    public boolean updateAvatarAndNickName(@RequestBody SysUser updateUserInfo){
        SysUser userInfo = LoginUtil.getUserInfo();

        SysUser sysUser = sysUserService.getById(userInfo.getUserId());
        sysUser.setAvatar(updateUserInfo.getAvatar());
        sysUser.setNickName(updateUserInfo.getNickName());
        return sysUserService.updateById(sysUser);
    }

    @GetMapping("/pageComplexAll")
    @ApiOperation(value = "复杂分页查询")
    public Page<SysUserVo> pageComplexAll(Page<SysUser> page, UserDto userDto) {
//        Page<SysUser> roadPage = page.toPage();
//
//        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(SysUser.COL_DEL_FLAG,0);
//
//        if (StrUtil.isNotEmpty(userDto.getEnable())){
//            queryWrapper.in( "enable", Arrays.stream(userDto.getEnable().split(",")).collect(Collectors.toList()));
//
//        }
//
//        if (StrUtil.isNotEmpty(userDto.getIdentityIds())){
//            //todo 这里是角色
//            List<String> IdentityIdList = Arrays.stream(userDto.getIdentityIds().split(",")).collect(Collectors.toList());
//            List<SysUserRole> userRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>().in("role_id", IdentityIdList));
//
//            if (userRoleList.size() == 0){
//                queryWrapper.eq( SysUser.COL_USER_ID, 0);
//            }
//
//            if (IdentityIdList.size() > 0 && userRoleList.size() > 0){
//                queryWrapper.in( SysUser.COL_USER_ID, userRoleList.stream().map(SysUserRole::getUserId).collect(Collectors.toList()));
//            }
//        }
//        if (StringUtils.isNotEmpty(userDto.getKeyword())){
//            List<SysDept> deptList = deptService.list(new QueryWrapper<SysDept>().like(SysDept.COL_DEPT_NAME, userDto.getKeyword()));
//
//            queryWrapper.like("user_name", userDto.getKeyword())
//                            .or()
//                            .like("nick_name", userDto.getKeyword())
//                            .or()
//                            .like(SysUser.COL_USER_CODE,userDto.getKeyword())
//                            .or()
//                            .like(SysUser.COL_PHONE,userDto.getKeyword());
//
//            if (deptList.size() > 0){
//                queryWrapper.in(SysUser.COL_DEPT_CODE,deptList.stream().map(SysDept::getCode).collect(Collectors.toList()));
//            }
//        }
//
//        //根据部门ID查询部门
//
//        String deptListStr = userDto.getDeptList();
//        //0:本部门 ，1：下级部门
//        SysUser userInfo = LoginUtil.getUserInfo();
//        if (StrUtil.isNotEmpty(deptListStr)){
//            String[] split = deptListStr.split(",");
//            if (split.length > 0){
//                List<String> deptCodeList = new ArrayList<>();
//                List<String> deptListStrInfo = Arrays.stream(split).collect(Collectors.toList());
//                for (String deptdefine:deptListStrInfo){
//                    if ("0".equals(deptdefine)) {
//
//                        deptCodeList.add(userInfo.getDeptCode());
//                    } else if ("1".equals(deptdefine)) {
//                        //除开自己
//                        List<String> deptCodes = sysUserService.getDeptAndSonExcludeOwnByDeptCode(userInfo.getDeptCode());
//                        if (deptCodes.size() > 0){
//                            deptCodeList.addAll(deptCodes);
//                        }
//
//
//                    }
//                }
//
//                if (deptCodeList.size() > 0){
//                    queryWrapper.in(SysUser.COL_DEPT_CODE, deptCodeList);
//                }else {
//                    deptCodeList.add("-1");
//                    queryWrapper.in(SysUser.COL_DEPT_CODE, deptCodeList);
//                }
//
//            }
//
//        }
////        else {
////            if (userDto.getDeptId() != null){
////                SysDept sysDept = deptService.getById(userDto.getDeptId());
////
////
////                List<String> deptAndSon = sysUserService.getDeptAndSonByDeptCode(sysDept.getCode());
////                if (deptAndSon.size() > 0){
////                    queryWrapper.in(SysUser.COL_DEPT_CODE, deptAndSon);
////                }
////
////            }
////        }
//
//        if (userDto.getDeptId() != null){
//            SysDept sysDept = deptService.getById(userDto.getDeptId());
//
//
//            List<String> deptAndSon = sysUserService.getDeptAndSonByDeptCode(sysDept.getCode());
//            if (deptAndSon.size() > 0){
//                queryWrapper.in(SysUser.COL_DEPT_CODE, deptAndSon);
//            }
//
//        }
//
//
//
//
//
//
//
//        Page<SysUser> pageList = sysUserService.page(roadPage,queryWrapper );
//        //处理判断是否激活
//
//
//        List<SysUser> userList = pageList.getRecords();
//
//        List<SysUserVo> userVoList = userList.stream().map(user -> {
//            SysUserVo sysUserVo = new SysUserVo();
//            BeanUtil.copyProperties(user, sysUserVo);
//            sysUserVo.setHasActivation(0);
//
//            CardInfoUser cardInfoUser = cardInfoUserService.getOne(new QueryWrapper<CardInfoUser>().eq(CardInfoUser.COL_USER_CODE, sysUserVo.getUserCode())
//                    .eq(SysUser.COL_DEL_FLAG, 0));
//
//            if (cardInfoUser != null) {
//                sysUserVo.setHasActivation(1);
//                sysUserVo.setActivationTime(cardInfoUser.getCreatedTime());
//            }
//
//            return sysUserVo;
//        }).collect(Collectors.toList());
//
//        //构造返回page
//        Page<SysUserVo> userVoPage = new Page<>();
//        BeanUtil.copyProperties(pageList,userVoPage);
//        userVoPage.setRecords(userVoList);

        HashSet<String> deptCodeList = new HashSet<>();


        String deptListStr = userDto.getDeptList();
//        //0:本部门 ，1：下级部门
        SysUser userInfo = LoginUtil.getUserInfo();
        if (StrUtil.isNotEmpty(deptListStr)){
            String[] split = deptListStr.split(",");
            if (split.length > 0){
                List<String> deptListStrInfo = Arrays.stream(split).collect(Collectors.toList());
                for (String deptdefine:deptListStrInfo){
                    if ("0".equals(deptdefine)) {

                        deptCodeList.add(userInfo.getDeptCode());
                    } else if ("1".equals(deptdefine)) {
                        //除开自己
                        List<String> deptCodes = sysUserService.getDeptAndSonExcludeOwnByDeptCode(userInfo.getDeptCode());
                        if (deptCodes.size() > 0){
                            deptCodeList.addAll(deptCodes);
                        }


                    }
                }
            }
        }
        if (userDto.getDeptId() != null){
            SysDept dept = deptService.getById(userDto.getDeptId());
            List<String> deptAndSonByDeptCode = sysUserService.getDeptAndSonByDeptCode(dept.getCode());
            deptCodeList.addAll(deptAndSonByDeptCode);
        }


        if (deptCodeList.size() > 0){
            List<String> collect = deptCodeList.stream().collect(Collectors.toList());
            userDto.setDeptCodeList(collect);
        }

        Page<SysUserVo> sysUserVoPage = sysUserService.pageComplexAll(page, userDto);

        return sysUserVoPage;
    }


    @GetMapping("/getAll")
    @ApiOperation(value = "获取所有用户")
    public CommRes getAll() {
        List<SysUser> list = sysUserService.list(new QueryWrapper<SysUser>().eq(SysUser.COL_DEL_FLAG,0));
        if (CollUtil.isNotEmpty(list)) {
            List<FlowAssigneVo> collect = list.stream().map(sysUser -> FlowAssigneVo.builder().name(sysUser.getNickName()).value(sysUser.getUserId() + "").build()).collect(Collectors.toList());
            collect.add(0, FlowAssigneVo.builder().name("请选择").value("").build());
            collect.add(1, FlowAssigneVo.builder().name("当前用户").value("CurrentUser").build());
            return CommRes.ok(collect);
        }
        return CommRes.ok();
    }

    @PostMapping
    @ApiOperation(value = "新增或者更新")
    public CommRes saveOrUpdate(@RequestBody SysUserVo param) {
        return sysUserService.saveOrUpdate(param);
    }


    @PostMapping("/saveOrUpdateBatch")
    @ApiOperation(value = "批量新增或者更新")
    public boolean saveOrUpdateBatch(@RequestBody List<SysUserSyncVo> sysUserVoList) {

        for (SysUserSyncVo param:sysUserVoList){
            try {
                sysUserService.saveOrUpdateSync(param);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return true;


    }

    public boolean saveUserRole(Long userId, List<Integer> roleIds) {
        sysUserRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));

        List<SysUserRole> sysUserRoles = new ArrayList<>();
        roleIds.forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(Long.valueOf(roleId));
            sysUserRole.setUserId(userId);
            sysUserRoles.add(sysUserRole);
        });
        return sysUserRoleService.saveBatch(sysUserRoles);
    }


    @PutMapping("/updatePwd")
    @ApiOperation(value = "更新用户密码")
//    @SaCheckPermission("user.update.pwd")
    public CommRes updatePwd(@RequestBody PwdQo param) {

        if (!StrUtil.equals(param.getNewPassword(), param.getConfirmPassword())) {
            return CommRes.error("500", "两次输入密码不一致");
        }
        long userId = StpUtil.getLoginIdAsLong();
        SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUserId, userId)
                .eq(SysUser::getPassword, SecureUtil.sha256(param.getOldPassword())));
        if (sysUser == null) {
            return CommRes.error("500", "旧密码错误");
        }
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPassword(SecureUtil.sha256(param.getNewPassword()));
        sysUserService.updateById(user);
        return CommRes.ok();
    }

    @PutMapping("/resetPwd/{userId}")
    @ApiOperation(value = "重置用户密码")
//    @SaCheckPermission("user.reset.pwd")
    public CommRes resetPwd(@PathVariable Long userId) {
        SysUser user = sysUserService.getById(userId);

        user.setPassword(SecureUtil.sha256(lakerConfig.getDefaultPwd()));
        sysUserService.updateById(user);
        return CommRes.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询")
    public CommRes get(@PathVariable Long id) {

        SysUser user = sysUserService.getById(id);
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtil.copyProperties(user,sysUserVo);

        List<SysUserRole> sysUserRoleList = sysUserRoleService.list(new QueryWrapper<SysUserRole>().eq("user_id", user.getUserId()));

        if (sysUserRoleList.size() > 0){
            List<Long> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().in("role_id", roleIdList));
            sysUserVo.setRoleList(roleList);
        }

        //查询部门
        SysDept dept = deptService.getById(user.getDeptId());
        if (dept != null){
            sysUserVo.setDeptInfo(dept);
        }

        sysUserVo.setHasActivation(0);

        CardInfoUser cardInfoUser = cardInfoUserService.getOne(new QueryWrapper<CardInfoUser>().eq(CardInfoUser.COL_USER_CODE, sysUserVo.getUserCode())
                .eq(SysUser.COL_DEL_FLAG, 0));

        if (cardInfoUser != null) {
            sysUserVo.setHasActivation(1);
            sysUserVo.setActivationTime(cardInfoUser.getCreatedTime());
        }

        return CommRes.ok(sysUserVo);
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "根据ids批量删除")
    public CommRes delete(String ids) {
        String[] split = ids.split(",");
        List<String> idList = Arrays.stream(split).filter(one -> StrUtil.isNotEmpty(one)).collect(Collectors.toList());

        return CommRes.ok(sysUserService.remove(new QueryWrapper<SysUser>().in(SysUser.COL_USER_ID, idList)));
    }

    @PostMapping("/deleteByPhone")
    @ApiOperation(value = "根据电话号码批量删除")
    public CommRes deleteByPhone(@RequestBody List<String> phoneList) {
        if (phoneList.size() <= 0){
            return CommRes.error("500","手机号不能传空，删除失败");
        }
        //删除该用户的领卡
        for (String phone:phoneList){
            SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq(SysUser.COL_PHONE, phone));
            if (user != null){
                cardInfoUserService.remove(new QueryWrapper<CardInfoUser>().eq(CardInfoUser.COL_USER_CODE,user.getUserCode()));
            }
        }


        boolean remove = sysUserService.remove(new QueryWrapper<SysUser>().in(SysUser.COL_PHONE, phoneList));
        if (!remove){
            throw new BusinessException("删除失败");
        }


        return CommRes.ok();
    }

    @GetMapping("/getRoles")
    public CommRes edit(Long userId) {
        List<SysRole> allRole = sysRoleService.list(null);
        if (userId != null) {
            List<SysUserRole> myRole = sysUserRoleService.list(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
            allRole.forEach(sysRole -> {
                myRole.forEach(sysUserRole -> {
                    if (sysRole.getRoleId().equals(sysUserRole.getRoleId())) {
                        sysRole.setChecked(true);
                    }
                });
            });
        }
        return CommRes.ok(allRole);
    }


    @DeleteMapping("/batch/{ids}")
    @ApiOperation(value = "根据批量删除ids删除")
//    @SaCheckPermission("dict.delete")
    public CommRes batchRemove(@PathVariable Long[] ids) {
        return CommRes.ok(sysUserService.removeByIds(CollUtil.toList(ids)));
    }


    /**
     * 导入模版下载
     */
    @GetMapping("/modelDownload")
    @ApiOperation(value = "导入模版下载")
    public File modelDownload() {
        try {
            DfsUtil dfsUtil = new DfsUtil();

            SysKeyValue keyValue = keyValueService.getOne(new QueryWrapper<SysKeyValue>().eq(SysKeyValue.COL_SYS_KEY, SysEnums.USER_INPORT_MODEL_DOWNLOAD));
            File download = dfsUtil.download(keyValue.getSysValue());
            return download;
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("未上传导入模版，请联系管理员");
        }
    }


    /**
     * 批量导入新成员
     * @return
     */
    @PostMapping("/importNewUser")
    @ApiOperation(value = "批量导入新成员")
    public CommRes importNewUser(@RequestParam("file") MultipartFile multipartFile) {
        try {
            ImportParams params = new ImportParams();
            params.setHeadRows(12);
//             params.setTitleRows(0);
            List<UserImportDto> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(),
                    UserImportDto.class, params);
            for (int i = result.size()-1 ; i>=0;i--){
                if (result.get(i).getUserName() == null){
                    result.remove(i);
                }else {

                }
            }

            CommRes.ok();
        }catch (Exception e){
            log.error("导入异常");
        }
        return CommRes.error("导入异常");
    }

    /**
     * 导出用户信息
     */
    @GetMapping("/userExport")
    @ApiOperation(value = "导出用户信息")
    public DfsUtil.DfsFile userExport(SysUserExport userExport) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();

        if (userExport != null && StrUtil.isNotEmpty(userExport.getIds())){
            String ids = userExport.getIds();
            List<String> idList = Arrays.stream(ids.split(",")).filter(StrUtil::isNotEmpty).collect(Collectors.toList());
            wrapper.in(SysUser.COL_USER_ID,idList);
        }

        List<CardInfoUser> cardInfoUserList = cardInfoUserService.list(new QueryWrapper<CardInfoUser>()
                .eq(SysUser.COL_DEL_FLAG, 0));

        List<SysUser> list = sysUserService.list(wrapper);
        List<SysUserExport> sysUserExportList = list.stream().map(user -> {
            SysUserExport sysUserExport = new SysUserExport();
            BeanUtil.copyProperties(user, sysUserExport);

            sysUserExport.setHasActivation(0);

            List<CardInfoUser> cardInfoUsers = cardInfoUserList.stream()
                    .filter(cardInfoUser -> cardInfoUser.getUserCode().equals(sysUserExport.getUserCode()))
                    .collect(Collectors.toList());


            if (cardInfoUsers.size() > 0) {
                CardInfoUser cardInfoUser = cardInfoUsers.get(0);
                sysUserExport.setHasActivation(1);
                sysUserExport.setActivationTime(cardInfoUser.getCreatedTime());
            }

            return sysUserExport;
        }).collect(Collectors.toList());

        DfsUtil dfsUtil = new DfsUtil();
        try {
            File file = FileUtil.createTempFile("用户信息名单", ".xls", new File("./"), true);
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户信息名单","用户信息名单"), SysUserExport.class, sysUserExportList);
            BufferedOutputStream outputStream = FileUtil.getOutputStream(file);
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            DfsUtil.DfsFile upload = dfsUtil.upload(file);
            return upload;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new BusinessException("导出异常");

    }

    /**
     * 根据部门查询用户
     *      包含数据下穿
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "根据部门查询用户（带下穿数据）")
    public CommRes<Page<SysUser>> getUserListByDeptPage(Page<SysUser> page, Long deptId, String keyword) {
        //查询这个deptId以及下属deptId
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        if (deptId != null){
            List<Long> deptAndSon = sysUserService.getDeptAndSon(deptId);
            wrapper.in(SysUser.COL_DEPT_ID, deptAndSon);
            wrapper.eq(SysUser.COL_DEL_FLAG, 0);

        }

        if (StrUtil.isNotEmpty(keyword)){
            wrapper.like(SysUser.COL_NICK_NAME,keyword)
                    .or()
                    .like(SysUser.COL_USER_CODE,keyword)
                    .or()
                    .like(SysUser.COL_PHONE,keyword)
                    .or()
                    .like(SysUser.COL_TAG,keyword);
        }
        Page<SysUser> userPage = sysUserService.page(page, wrapper);

        return CommRes.ok(userPage);
    }

    /**
     * 根据部门查询用户
     *      总人数和，激活，未激活数量
     * @return
     */
    @GetMapping("/getUserSituation")
    @ApiOperation(value = "根据部门查询用户，总人数和，激活，未激活数量")
    public CommRes<UserDeptInfo> getUserSituation(Long deptId) {
        if (deptId == null){
            throw new BusinessException("必填参数不能为空");
        }
        SysDept sysde = deptService.getById(deptId);


        List<String> deptCode = sysUserService.getDeptAndSonByDeptCode(sysde.getCode());


        UserDeptInfo userDeptInfo = new UserDeptInfo();
        int all = sysUserService.count(new QueryWrapper<SysUser>().in(SysUser.COL_DEPT_CODE, deptCode)
                .eq(SysUser.COL_DEL_FLAG,0));
        userDeptInfo.setAll(all);
        //考虑领卡的才叫
        List<CardInfoUser> list = cardInfoUserService.list(new QueryWrapper<CardInfoUser>()
                .eq(SysUser.COL_DEL_FLAG, 0));

        QueryWrapper<SysUser> wrapper = new QueryWrapper<SysUser>().in(SysUser.COL_DEPT_CODE, deptCode)
                .eq(SysUser.COL_ENABLE, 1)
                .eq(SysUser.COL_DEL_FLAG, 0);

        if (list.size() > 0){
            List<String> userCodeList = list.stream().map(CardInfoUser::getUserCode).collect(Collectors.toList());
            wrapper.in(SysUser.COL_USER_CODE,userCodeList);
        }

        int enable = sysUserService.count(wrapper);


        userDeptInfo.setEnable(enable);

        int unable = all - enable;
        userDeptInfo.setUnable(unable);

        return CommRes.ok(userDeptInfo);
    }

    @PostMapping("/moveUser")
    @ApiOperation(value = "移动成员")
    public CommRes moveUser(@RequestBody UserMoveVo userMoveVo) {
        if (userMoveVo.getUserList().size() <= 0 && StrUtil.isNotEmpty(userMoveVo.getDeptCode())){
            throw new BusinessException("必填参数不能为空");
        }
        List<SysUser> userList = userMoveVo.getUserList();
//        Long deptId = userMoveVo.getDeptId();
        SysDept sysDept = deptService.getOne(new QueryWrapper<SysDept>().eq(SysDept.COL_CODE, userMoveVo.getDeptCode()));

        List<Long> userIdList = userList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        List<SysUser> sysUserList = sysUserService.list(new QueryWrapper<SysUser>().in(SysUser.COL_USER_ID, userIdList)
                .eq(SysUser.COL_DEL_FLAG,0));

        List<SysUser> resultUserList = sysUserList.stream().map(one -> {
//            one.setDeptId(sysDept.getDeptId());
            one.setDeptCode(sysDept.getCode());
            one.setDeptName(sysDept.getDeptName());
            return one;
        }).collect(Collectors.toList());

        sysUserService.updateBatch(resultUserList);

        return CommRes.ok();
    }

    @GetMapping("/writeOff")
    @ApiOperation(value = "用户注销")
    public Boolean writeOff(String ids) {
        if (StrUtil.isNotEmpty(ids)){
            String[] split = ids.split(",");
            List<String> idList = Arrays.stream(split).filter(StrUtil::isNotEmpty).collect(Collectors.toList());
            List<SysUser> sysUserList = sysUserService.list(new QueryWrapper<SysUser>().in(SysUser.COL_USER_ID, idList));

            for (SysUser user : sysUserList) {
                user.setDelFlag(1);
            }
            return sysUserService.updateBatchById(sysUserList);
        }else {
            return false;
        }

    }


}


//    @PostMapping("/httpAdd")
//    @ApiOperation(value = "通过http新增")
//    @Inner(value = false)
//    public CommRes httpAdd(@RequestBody UserEncryptData userEncryptData) {
//
//        //todo 通过appKey 加密数据，然后
//        String publicKey = userEncryptData.getPublicKey();
//        //todo 在配置中查询key对应的privateKey
//        String privateKey = "";//查询配置表
//
//        //todo 根据privateKey解密数据
//        RSA rsa = new RSA(privateKey, publicKey);
//
//        String rowData = userEncryptData.getRowData();
//        if (StrUtil.isEmpty(rowData)){
//            throw new BusinessException("加密内容不能为空");
//        }
//        //SysUserVo
//        String userVo = rsa.decryptStr(rowData, KeyType.PrivateKey);
//        SysUserVo sysUserVo = JSONUtil.toBean(userVo, SysUserVo.class);
//
//
//        if (sysUserVo.getDeptId() == null) {
//            return CommRes.error("500", "请选择部门");
//        }
//
//        if (sysUserVo.getUserId() == null) {
//            // 只有超级管理员才能创建用户
//
//            String password = sysUserVo.getPassword();
//            sysUserVo.setPassword(SecureUtil.sha256(password));
//            sysUserVo.setCreateTime(new Date());
//            sysUserVo.setUserCode(sysUserVo.getPhone());
//
//            //查询根据部门id查询部门信息
//            SysDept deptInfo = deptService.getById(sysUserVo.getDeptId());
//            sysUserVo.setDeptName(deptInfo.getDeptName());
//            sysUserVo.setDeptCode(deptInfo.getCode());
//
//            //查询出当前学校的信息
//            List<SysSchoolInfo> schoolInfoList = schoolInfoService.list(new QueryWrapper<SysSchoolInfo>().eq(SysSchoolInfo.COL_DEL_FLAG,0));
//            if (schoolInfoList.size() > 0){
//                SysSchoolInfo schoolInfo = schoolInfoList.get(0);
//                sysUserVo.setSchoolId(schoolInfo.getId());
//                sysUserVo.setSchoolName(schoolInfo.getName());
//                sysUserVo.setSchoolCode(schoolInfo.getSchoolCode());
//            }
//
//            sysUserService.save(sysUserVo);
//            if (StrUtil.isNotBlank(sysUserVo.getRoleIds())) {
//                this.saveUserRole(sysUserVo.getUserId(), Arrays.asList(sysUserVo.getRoleIds().split(",")));
//            }
//        } else {
//            userOperateLogService.saveUserLog(sysUserVo);
//
//            sysUserService.saveOrUpdate(sysUserVo);
//            if (StrUtil.isNotBlank(sysUserVo.getRoleIds())) {
//                this.saveUserRole(sysUserVo.getUserId(), Arrays.asList(sysUserVo.getRoleIds().split(",")));
//            }
//
//
//        }
//        return CommRes.ok(sysUserService.saveOrUpdate(sysUserVo));
//    }


